package utility.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

public class Upload {

	private static final String SERVER = "localhost";
	private static final int PORT = 21;
	private static final String USER = "anonymous";
	private static final String PASSWORD = "";

	public static void main(String[] args) {
		boolean ret = false;

		try {

			int i = 5;
			int a = 31 * i;
			int b =  (i << 5) - i;
			String filePath = "C:/var/adptg/marin/2013-09-03/campaign_2_2013-09-03_411.txt";
			int index = filePath.lastIndexOf("/");
			String fileName = filePath.substring(index + 1);

			FTPClient ftper = Upload.ftpLogin();
			if(ftper == null) return;
			FTPFile f[] = ftper.listDirectories();

			for (FTPFile ftpFile : f) {
				System.out.println(ftpFile.getName());
			}

			String[] folders = null;
			String marinDir =  "";
			//if(marinDir != null && marinDir.length()>0)
				folders = marinDir.split(",");

			for (String folder : folders) {
				File file = new File(filePath);
				InputStream inputStream = new FileInputStream(file);
				boolean result = ftper.storeFile("/"+folder+"/"+fileName, inputStream);
				if(result) ret = result;
				inputStream.close();
			}
		} catch(Exception ex){
			System.out.println("error");
			System.out.println("error " + ret);
		}finally {
			//System.out.println("error 1" + ret);
		}

		System.out.println("error " + ret);
	}

	private static FTPClient ftpLogin() {
		try {
			FTPClient ftper = new FTPClient();
			ftper.connect(SERVER, PORT);
			boolean login = ftper.login(USER, PASSWORD);
			return login ? ftper : null;
		} catch (Exception e) {
			return null;
		} finally {
		}
	}

	private boolean ftpUpload(FTPClient ftper, String filePath) {
		int index = filePath.lastIndexOf("/");
		String fileName = filePath.substring(index + 1);
		try {
			File file = new File(filePath);
			InputStream inputStream = new FileInputStream(file);
			boolean result = ftper.storeFile(fileName, inputStream);
			inputStream.close();
			return result;
		} catch (Exception e) {
			return false;
		} finally {
		}
	}

	private void ftpLogout() {
		try {
			//if (ftper != null && ftper.isConnected()) {
			//	ftper.logout();
			//	ftper.disconnect();
			//}
		} catch (Exception e) {
		}
	}

}
